<template>
  <div class="ranking-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <button @click="goBack" class="back-btn">← 返回</button>
        <div class="header-title">
          <div class="trophy-icon">🏆</div>
          <h1 class="page-title">成绩排行榜</h1>
          <div class="subtitle">{{ homeworkTitle }}</div>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-label">参与人数</span>
            <span class="stat-value">{{ students.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">平均分</span>
            <span class="stat-value">{{ averageScore.toFixed(1) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 前三名特殊展示 -->
      <div class="podium-section" v-if="students.length >= 1">
        <div class="podium-container">
          <!-- 第二名 -->
          <div class="podium-item second-place" v-if="students.length >= 2">
            <div class="podium-rank">
              <div class="rank-medal silver">🥈</div>
              <div class="rank-number">2</div>
            </div>
            <div class="student-avatar">
              <img :src="students[1].avatar || '/default-avatar.png'" :alt="students[1].name" />
            </div>
              <div class="student-info">
                <div class="student-name">{{ students[1].name }}</div>
                <div class="student-score">{{ students[1].score.toFixed(1) }}分</div>
              </div>
            <div class="podium-bar second"></div>
          </div>

          <!-- 第一名 -->
          <div class="podium-item first-place" v-if="students.length >= 1">
            <div class="podium-rank">
              <div class="rank-medal gold">🥇</div>
              <div class="rank-number">1</div>
            </div>
            <div class="student-avatar champion">
              <img :src="students[0].avatar || '/default-avatar.png'" :alt="students[0].name" />
              <div class="crown">👑</div>
            </div>
            <div class="student-info">
              <div class="student-name champion-name">{{ students[0].name }}</div>
              <div class="student-score champion-score">{{ students[0].score.toFixed(1) }}分</div>
            </div>
            <div class="podium-bar first"></div>
          </div>

          <!-- 第三名 -->
          <div class="podium-item third-place" v-if="students.length >= 3">
            <div class="podium-rank">
              <div class="rank-medal bronze">🥉</div>
              <div class="rank-number">3</div>
            </div>
            <div class="student-avatar">
              <img :src="students[2].avatar || '/default-avatar.png'" :alt="students[2].name" />
            </div>
            <div class="student-info">
              <div class="student-name">{{ students[2].name }}</div>
              <div class="student-score">{{ students[2].score.toFixed(1) }}分</div>
            </div>
            <div class="podium-bar third"></div>
          </div>
        </div>
      </div>

      <!-- 完整排名列表 -->
      <div class="ranking-list">
        <div class="list-header">
          <h2 class="list-title">
            <span class="star-icon">⭐</span>
            完整排名
            <span class="star-icon">⭐</span>
          </h2>
        </div>

        <div class="ranking-table">
          <div class="table-header">
            <div class="header-rank">排名</div>
            <div class="header-student">学生</div>
            <div class="header-score">分数</div>
            <div class="header-percentage">得分率</div>
          </div>

          <div class="table-body">
            <div 
              v-for="(student, index) in students" 
              :key="student.id"
              :class="[
                'ranking-row',
                {
                  'top-three': index < 3,
                  'first-place-row': index === 0,
                  'second-place-row': index === 1,
                  'third-place-row': index === 2
                }
              ]"
            >
              <div class="row-rank">
                <div class="rank-display">
                  <span v-if="index === 0" class="rank-medal">🥇</span>
                  <span v-else-if="index === 1" class="rank-medal">🥈</span>
                  <span v-else-if="index === 2" class="rank-medal">🥉</span>
                  <span v-else class="rank-number">{{ index + 1 }}</span>
                </div>
              </div>

              <div class="row-student">
                <div class="student-avatar-small">
                  <img :src="student.avatar || '/default-avatar.png'" :alt="student.name" />
                </div>
                <div class="student-details">
                  <div class="student-name">{{ student.name }}</div>
                </div>
              </div>

              <div class="row-score">
                <div class="score-value">{{ student.score.toFixed(1) }}</div>
                <div class="score-total">/ {{ totalScore }}</div>
              </div>

              <div class="row-percentage">
                <div class="percentage-bar">
                  <div 
                    class="percentage-fill" 
                    :style="{ width: (student.score / totalScore * 100) + '%' }"
                  ></div>
                </div>
                <div class="percentage-text">{{ ((student.score / totalScore) * 100).toFixed(1) }}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在加载排名数据...</div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && students.length === 0" class="empty-state">
        <div class="empty-icon">📊</div>
        <div class="empty-title">暂无成绩数据</div>
        <div class="empty-description">当前作业还没有学生提交成绩</div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getHomeworkRank } from '@/api/homework'
import logger from '../utils/logger.js'

export default {
  name: 'StudentRanking',
  setup() {
    // Vue Router
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const homeworkId = ref(null)
    const homeworkTitle = ref('加载中...')
    const totalScore = ref(100)
    
    // 学生成绩数据
    const students = ref([
      {
        id: 1,
        name: '张三',
        score: 98.5,
        avatar: null
      },
      {
        id: 2,
        name: '李四',
        score: 95.2,
        avatar: null
      },
      {
        id: 3,
        name: '王五',
        score: 92.8,
        avatar: null
      },
      {
        id: 4,
        name: '赵六',
        score: 89.6,
        avatar: null
      },
      {
        id: 5,
        name: '陈七',
        score: 87.3,
        avatar: null
      },
      {
        id: 6,
        name: '刘八',
        score: 85.1,
        avatar: null
      },
      {
        id: 7,
        name: '周九',
        score: 82.7,
        avatar: null
      },
      {
        id: 8,
        name: '吴十',
        score: 79.4,
        avatar: null
      }
    ])

    // 计算属性
    const averageScore = computed(() => {
      if (students.value.length === 0) return 0
      const total = students.value.reduce((sum, student) => sum + student.score, 0)
      return total / students.value.length
    })

    // 方法
    const loadHomeworkInfo = () => {
      logger.log('📋 [StudentRanking] 加载作业信息...')
      
      // 从Vue Router的query参数获取作业ID
      const urlHomeworkId = router.currentRoute.value.query.homeworkId
      
      // 从localStorage获取作业信息
      const savedHomeworkInfo = localStorage.getItem('rankingHomework')
      
      if (urlHomeworkId) {
        homeworkId.value = urlHomeworkId
        logger.log('📋 [StudentRanking] 从URL获取作业ID:', urlHomeworkId)
      }
      
      if (savedHomeworkInfo) {
        try {
          const homeworkInfo = JSON.parse(savedHomeworkInfo)
          homeworkId.value = homeworkInfo.id || homeworkId.value
          homeworkTitle.value = homeworkInfo.title || '未知作业'
          totalScore.value = homeworkInfo.totalScore || 100
          
          logger.log('📋 [StudentRanking] 从localStorage获取作业信息:', homeworkInfo)
        } catch (error) {
          logger.error('❌ [StudentRanking] 解析作业信息失败:', error)
        }
      }
      
      if (!homeworkId.value) {
        logger.error('❌ [StudentRanking] 未找到作业ID')
        homeworkTitle.value = '未知作业'
      }
    }

    const loadRankingData = async () => {
      loading.value = true
      try {
        logger.log('📊 [StudentRanking] 加载排名数据...')
        logger.log('📊 [StudentRanking] 作业ID:', homeworkId.value)
        
        if (homeworkId.value) {
          try {
            // 调用真实的API获取排名数据
            logger.log('🌐 [StudentRanking] 调用API获取排名数据...')
            const response = await getHomeworkRank(homeworkId.value)
            
            logger.log('✅ [StudentRanking] API响应:', response)
            
            // 处理后端返回的数据格式: { code: 0, message: "操作成功", data: [...] }
            if (response && response.code === 0 && response.data && Array.isArray(response.data)) {
              // 转换后端数据格式为前端需要的格式
              students.value = response.data.map((item, index) => ({
                id: item.studentId,
                name: item.studentName,
                score: item.score,
                ranking: item.ranking,
                submitTime: item.submitTime,
                avatar: null // 后端暂时没有头像数据
              }))
              
              logger.log('✅ [StudentRanking] 使用API数据，学生数量:', students.value.length)
              logger.log('📊 [StudentRanking] 转换后的学生数据:', students.value)
            } else {
              throw new Error('API返回数据格式不正确或code不为0')
            }
          } catch (error) {
            logger.warn('⚠️ [StudentRanking] API调用失败，使用模拟数据:', error)
            
            // 如果API调用失败，使用模拟数据
            students.value = generateMockRankingData(homeworkId.value)
            logger.log('📊 [StudentRanking] 使用模拟数据')
          }
        } else {
          // 没有作业ID，使用默认模拟数据
          students.value = generateMockRankingData('default')
        }
        
        // 确保按分数排序（从高到低）
        students.value.sort((a, b) => b.score - a.score)
        
        logger.log('✅ [StudentRanking] 排名数据加载完成')
        logger.log('📊 [StudentRanking] 学生数量:', students.value.length)
      } catch (error) {
        logger.error('❌ [StudentRanking] 加载排名数据失败:', error)
        // 显示错误状态或者默认数据
      } finally {
        loading.value = false
      }
    }

    const generateMockRankingData = (hwId) => {
      // 根据作业ID生成不同的模拟数据
      const baseStudents = [
        { name: '张三' },
        { name: '李四' },
        { name: '王五' },
        { name: '赵六' },
        { name: '陈七' },
        { name: '刘八' },
        { name: '周九' },
        { name: '吴十' }
      ]
      
      return baseStudents.map((student, index) => ({
        id: index + 1,
        name: student.name,
        score: Math.max(60, 100 - index * (Math.random() * 8 + 2)), // 随机生成60-100分，会自动产生小数
        avatar: null
      }))
    }

    const goBack = () => {
      // 使用Vue Router返回上一页
      router.go(-1)
    }

    // 生命周期
    onMounted(() => {
      loadHomeworkInfo()
      loadRankingData()
    })

    return {
      loading,
      homeworkId,
      homeworkTitle,
      totalScore,
      students,
      averageScore,
      loadHomeworkInfo,
      loadRankingData,
      goBack
    }
  }
}
</script>

<style scoped>
.ranking-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: 'Arial', sans-serif;
}

/* 页面头部 */
.page-header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 20px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.header-title {
  text-align: center;
  color: white;
}

.trophy-icon {
  font-size: 48px;
  margin-bottom: 10px;
  animation: bounce 2s infinite;
}

.page-title {
  font-size: 32px;
  margin: 0 0 5px 0;
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.subtitle {
  font-size: 16px;
  opacity: 0.9;
}

.header-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
  color: white;
}

.stat-label {
  display: block;
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: bold;
}

/* 主要内容 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

/* 领奖台区域 */
.podium-section {
  margin-bottom: 60px;
}

.podium-container {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 20px;
  margin-bottom: 40px;
}

.podium-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.podium-rank {
  margin-bottom: 20px;
  position: relative;
}

.rank-medal {
  font-size: 48px;
  display: block;
  margin-bottom: 10px;
  animation: glow 2s ease-in-out infinite alternate;
}

.rank-number {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.student-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 15px;
  position: relative;
  border: 4px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.student-avatar.champion {
  width: 100px;
  height: 100px;
  border: 5px solid #ffd700;
  box-shadow: 0 0 20px rgba(255, 215, 0, 0.5);
}

.student-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
}

.crown {
  position: absolute;
  top: -15px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 24px;
  animation: bounce 1s infinite;
}

.student-info {
  text-align: center;
  color: white;
  margin-bottom: 20px;
}

.student-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.champion-name {
  font-size: 22px;
  color: #ffd700;
}

.student-score {
  font-size: 16px;
  opacity: 0.9;
}

.champion-score {
  font-size: 20px;
  color: #ffd700;
  font-weight: bold;
}

.podium-bar {
  width: 80px;
  border-radius: 8px 8px 0 0;
  position: relative;
}

.podium-bar.first {
  height: 120px;
  background: linear-gradient(180deg, #ffd700, #ffed4e);
  box-shadow: 0 0 20px rgba(255, 215, 0, 0.3);
}

.podium-bar.second {
  height: 90px;
  background: linear-gradient(180deg, #c0c0c0, #e8e8e8);
  box-shadow: 0 0 15px rgba(192, 192, 192, 0.3);
}

.podium-bar.third {
  height: 60px;
  background: linear-gradient(180deg, #cd7f32, #e6a85c);
  box-shadow: 0 0 15px rgba(205, 127, 50, 0.3);
}

/* 排名列表 */
.ranking-list {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
}

.list-header {
  text-align: center;
  margin-bottom: 30px;
}

.list-title {
  font-size: 28px;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.star-icon {
  font-size: 24px;
  color: #ffd700;
  animation: twinkle 1.5s ease-in-out infinite alternate;
}

/* 表格样式 */
.ranking-table {
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: grid;
  grid-template-columns: 80px 1fr 120px 150px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  font-weight: bold;
  padding: 20px;
}

.header-rank,
.header-student,
.header-score,
.header-percentage {
  display: flex;
  align-items: center;
  justify-content: center;
}

.table-body {
  background: white;
}

.ranking-row {
  display: grid;
  grid-template-columns: 80px 1fr 120px 150px;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  align-items: center;
}

.ranking-row:hover {
  background: #f8f9ff;
  transform: translateX(5px);
}

.ranking-row.top-three {
  background: linear-gradient(90deg, rgba(255, 215, 0, 0.1), rgba(255, 255, 255, 0.1));
}

.ranking-row.first-place-row {
  background: linear-gradient(90deg, rgba(255, 215, 0, 0.2), rgba(255, 255, 255, 0.1));
  border-left: 5px solid #ffd700;
}

.ranking-row.second-place-row {
  background: linear-gradient(90deg, rgba(192, 192, 192, 0.2), rgba(255, 255, 255, 0.1));
  border-left: 5px solid #c0c0c0;
}

.ranking-row.third-place-row {
  background: linear-gradient(90deg, rgba(205, 127, 50, 0.2), rgba(255, 255, 255, 0.1));
  border-left: 5px solid #cd7f32;
}

.row-rank {
  display: flex;
  justify-content: center;
}

.rank-display {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f0f0f0;
  font-weight: bold;
}

.rank-medal {
  font-size: 24px;
}

.rank-number {
  font-size: 18px;
  color: #666;
}

.row-student {
  display: flex;
  align-items: center;
  gap: 15px;
  justify-content: center;
}

.student-avatar-small {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #e0e0e0;
}

.student-avatar-small img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
}

.student-details {
  text-align: center;
}

.student-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.student-id {
  font-size: 12px;
  color: #666;
}

.row-score {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  color: #4a90e2;
}

.score-total {
  font-size: 16px;
  color: #666;
}

.row-percentage {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.percentage-bar {
  width: 100px;
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.percentage-fill {
  height: 100%;
  background: linear-gradient(90deg, #4a90e2, #67b6ff);
  border-radius: 4px;
  transition: width 0.5s ease;
}

.percentage-text {
  font-size: 14px;
  font-weight: bold;
  color: #4a90e2;
}

/* 加载和空状态 */
.loading-container {
  text-align: center;
  padding: 60px 20px;
  color: white;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-left: 4px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

.loading-text {
  font-size: 16px;
  opacity: 0.9;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: white;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.empty-description {
  font-size: 16px;
  opacity: 0.8;
}

/* 动画效果 */
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

@keyframes glow {
  from {
    filter: drop-shadow(0 0 10px rgba(255, 215, 0, 0.5));
  }
  to {
    filter: drop-shadow(0 0 20px rgba(255, 215, 0, 0.8));
  }
}

@keyframes twinkle {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(1.2);
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
  }

  .header-stats {
    gap: 20px;
  }

  .podium-container {
    flex-direction: column;
    align-items: center;
  }

  .table-header,
  .ranking-row {
    grid-template-columns: 60px 1fr 80px 100px;
    padding: 15px 10px;
  }

  .row-student {
    flex-direction: column;
    gap: 8px;
  }

  .student-avatar-small {
    width: 40px;
    height: 40px;
  }

  .percentage-bar {
    width: 60px;
  }
}
</style>
